package com.xxxx.server.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminInfo;
import com.xxxx.server.pojo.PassInfo;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.utils.ConstantPropertiesUtil;
import com.xxxx.server.utils.JwtTokenUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-08-17
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

	@Resource
	private AdminMapper adminMapper;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Value("${jwt.tokenHead}")
	private String tokenHead;

	/**
	 * 登录
	 */
	@Override
	public RespBean login(String username, String password) {
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		if (null== userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
			return RespBean.error("用户名或密码不正确");
		}
		if (!userDetails.isEnabled()){
			return RespBean.error("账户被禁用，请联系管理员");
		}
		//设置用户对象至SpringSecurity全局上下文，方便其他地方使用
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
				null, userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		String token = jwtTokenUtil.generatorToken(userDetails);
		Map<String, Object> tokenMap = new HashMap<>();
		tokenMap.put("tokenHead",tokenHead);
		tokenMap.put("token",token);
		return RespBean.success("登录成功",tokenMap);
	}

	/**
	 * 根据用户名获取用户对象
	 */
	@Override
	public Admin getAdminByUserName(String username) {
		return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
	}

	/**
	 * 启用禁用
	 */
	@Override
	public void enabledChange(Boolean enabled, Integer id) {
		if(enabled == true){ // 启用状态
			adminMapper.enabledChange(id);
		}
		if(enabled == false){ // 禁用状态
			adminMapper.disableEnabled(id);
		}
	}

	/**
	 * 修改个人中心用户信息
	 */
	@Override
	public RespBean updateAdmin(AdminInfo adminInfo) {
		// 参数校验
		if(null == adminInfo.getName()){
			return RespBean.error("用户名不能为空");
		}
		if(null == adminInfo.getTelephone()){
			return RespBean.error("电话号码不能为空");
		}
		if (null == adminInfo.getPhone()){
			return RespBean.error("手机号码不能为空");
		}
		if(null == adminInfo.getAddress()){
			return RespBean.error("用户地址不能为空");
		}

		// 执行修改操作
		if(adminMapper.updateByInfo(adminInfo) < 1){
			return RespBean.error("修改失败");
		}

		return RespBean.success("修改成功");
	}

	/**
	 * 修改密码
	 */
	@Override
	public RespBean updatePass(PassInfo passInfo) {

		// 参数校验
		if(StringUtils.isBlank(passInfo.getOldPass())){
			return RespBean.error("旧密码不能为空");
		}
		if(StringUtils.isBlank(passInfo.getPass())){
			return RespBean.error("新密码不能为空");
		}
		if (StringUtils.isBlank(passInfo.getCheckPass())){
			return RespBean.error("确认密码不能为空");
		}

		// 旧密码是否正确
		String oldPassword = passInfo.getOldPass();
		if(!(passwordEncoder.matches(oldPassword,adminMapper.selectPasswordById(passInfo.getAdminId())))){
			return RespBean.error("旧密码不一致");
		}

		//新密码与旧密码不能相同
		String newPassword = passInfo.getPass();
		if(newPassword.equals(oldPassword)){
			return RespBean.error("新密码与旧密码不能相同");
		}

		//确认密码不一致
		String checkPassword = passInfo.getCheckPass();
		if(!(checkPassword.equals(newPassword))){
			return RespBean.error("确认密码不一致");
		}
		checkPassword = passwordEncoder.encode(checkPassword);
		passInfo.setCheckPass(checkPassword);

		if(adminMapper.updatePassword(passInfo) < 1){
			return RespBean.error("修改失败");
		}
		return RespBean.success("修改成功");
	}

	/**
	 *上传头像
	 */
	@Override
	public String uploadFileAvatar(MultipartFile file, Integer id) {
		// 上传头像到oss
		// 工具类获取值
		String endpoint = ConstantPropertiesUtil.END_POINT;
		String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
		String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
		String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

		try {
			// 创建OSSClient实例。
			OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

			// 上传文件流
			InputStream inputStream = file.getInputStream();

			// 获取文件名称
			String fileName = file.getOriginalFilename();

			// 1.在文件名称里面添加随机唯一的值
			String uuid = UUID.randomUUID().toString().replaceAll("-","");
			fileName = uuid + fileName;

			// 2. 把文件按日期进行分类
			// 2019/11/12/01.jpg
			// 获取当前日期
			String datePath = new DateTime().toString("yyyy/MM/dd");

			// 拼接
			fileName = datePath + "/" + fileName;

			// 调用oss方法实现上传
			// 第一个参数 Bucker名称
			// 第二个参数 上传到oss文件路径或文件名称
			// 第三个参数  上传文件输入流
			ossClient.putObject(bucketName, fileName, inputStream);

			// 关闭OSSClient。
			ossClient.shutdown();

			// 把上传之后文件路径返回
			// 需要把上传到阿里云oss路径手动拼接出来
			// https://zj-edu-1010.oss-cn-shanghai.aliyuncs.com/1.jpg

			String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

			adminMapper.updateUserFace(id, url);
			return url;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
